import requests
from bs4 import BeautifulSoup
import re
url = 'https://search.dangdang.com/?key=%CA%E9%B0%FC&act=input'

response = requests.get(url)
response.encoding = "gbk"
html = response.text
 # 正则提取商品名称和价格
product_pattern = r'<li[^>]*ddt-pit="\d+"[^>]*class="line\d+"[^>]*>.*?</li>'
product_matches = re.findall(product_pattern, html, re.S)
print("序号 价格\t\t\t\t\t\t\t 商品名称")
for item in product_matches:
    #提取商品序号
    ddt_pit_pattern = r'ddt-pit="(\d+)"'
    ddt_pit_match = re.search(ddt_pit_pattern, item)
    ddt_pit = ddt_pit_match.group(1) if ddt_pit_match else "未知"
    #提取商品文字介绍
    title_pattern = r'<a title="([^"]+)"'
    ddt_title_match = re.search(title_pattern, item)
    ddt_title = ddt_title_match.group(1) if ddt_title_match else "未知"
    #提取出商品的价格
    price_pattern = r'<span class="price_n">\s*&yen;\s*([\d.]+)\s*</span>'
    ddt_price_match = re.search(price_pattern,item)
    ddt_price = ddt_price_match.group(1) if ddt_price_match else "未知"

    print(f"{ddt_pit:>2}  {ddt_price:>6} {ddt_title:35}")



